package com.yonyou.pmclouds.discuss.impl;

import com.yonyou.pmclouds.basecom.bp.processor.AuditInfoInsertProcessor;
import com.yonyou.pmclouds.basecom.bp.template.SingleInsertBpTemplate;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.CommonProgramConsts;
import com.yonyou.pmclouds.discuss.entity.DiscussNoticeVO;
import com.yonyou.pmclouds.discuss.itf.DiscussNoticeInternalOperation;
import com.yonyou.pmclouds.discuss.mapper.DiscussNoticeMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DiscussNoticeInternalOperationImpl implements DiscussNoticeInternalOperation {

    @Autowired
    private DiscussNoticeMapper mapper;

    @Override
    public DiscussNoticeVO[] queryByReceiver(String receiver, int pageStart, int pageSize) {
        if (pageSize > CommonProgramConsts.DEFAULT_MAX_QUERY_SIZE) {
            pageSize = CommonProgramConsts.DEFAULT_MAX_QUERY_SIZE;
        }
        if (pageSize < CommonProgramConsts.DEFAULT_MIN_QUERY_SIZE) {
            pageSize = CommonProgramConsts.DEFAULT_MIN_QUERY_SIZE;
        }
        return mapper.queryByReceiver(receiver, pageStart, pageSize);
    }

    @Override
    public void insertNotices(DiscussNoticeVO[] notices) throws BusinessException {
        if (ArrayUtils.isEmpty(notices)) {
            return;
        }
        for (DiscussNoticeVO notice : notices) {
            SingleInsertBpTemplate<DiscussNoticeVO> bp = new SingleInsertBpTemplate<>(mapper);
            bp.addBeforeProcessor(new AuditInfoInsertProcessor<DiscussNoticeVO>());
            // TODO 暂时不需要通知
            bp.insert(notice);
        }
    }

    @Override
    public void makeNoticeRead(String noticeId, String receiver) throws BusinessException {
        mapper.makeNoticeRead(noticeId, receiver);
    }

    @Override
    public boolean hasUnreadNotice(String user) throws BusinessException {
        String receiver = mapper.hasUnreadNotice(user);
        return StringUtils.isNotEmpty(receiver);
    }

    @Override
    public int countUnreadNotice(String user) {
        return mapper.countUnreadByReceiver(user);
    }

    @Override
    public void deleteNotice(String noticeId) {
        mapper.delete(noticeId);
    }
}
